package cn.foo.web;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 服务端
 * @author Frank
 * @date 07-03
 */
public class SocketDemo {
    public static void main(String[] args) {
        //创建服务端的socket JPA
        System.out.println("服务端启动，等待连接");
        //定义图片存储的根路径
        String path = "E:"+ File.separator+"image";
        //try with resource
        try (ServerSocket server = new ServerSocket(8888);){
            //建立连接
            while (true){
                Socket socket = server.accept();
                System.out.println("连接成功！！");
                //lambda
                new Thread(()->{
                    //通过socket得到输入流
                    String fileName = System.currentTimeMillis()+".jpg";
                    try (InputStream is = socket.getInputStream();
                         //创建输出流\
                         FileOutputStream fos = new FileOutputStream(
                                 path+File.separator+fileName)){
                        //循环读取写入
                        int len = -1;
                        byte[] bufs = new byte[1024];
                        while ((len = is.read(bufs)) != -1){
                            fos.write(bufs,0,len);
                            fos.flush();
                        }
                        System.out.println("写入成功");
                        //释放资源
                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
